// 登录成功后显示悬浮球
function showFloatBall() {
    document.getElementById('floatBall').style.display = 'flex';
}

// 判断是否是IOS设备
function isiOS() {
    return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
}
function isMobile() {
    const userAgent = navigator.userAgent || navigator.vendor || window.opera;

    // 检查常见的移动设备关键词
    const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    return mobileRegex.test(userAgent);
}

// 判断是否是微信环境
function isWeixin() {
    const ua = window.navigator.userAgent.toLowerCase();
    // 微信6.0及以上版本的UA中包含'micromessenger'字样
    return (/micromessenger/i).test(ua) && !(/wxwork/i).test(ua);
}

function getQueryParam(name) {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

function isWebView() {
    const userAgent = navigator.userAgent.toLowerCase();

    // iOS WebView 检测
    const isIOSWebView = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(userAgent);

    // Android WebView 检测
    const isAndroidWebView = /; wv\).*Chrome\//.test(userAgent);

    // Facebook 应用内浏览器
    const isFacebookApp = /FBAN|FBAV/i.test(userAgent);

    // Instagram 应用内浏览器
    const isInstagramApp = /Instagram/i.test(userAgent);

    return isIOSWebView || isAndroidWebView || isFacebookApp || isInstagramApp;
}


// 账号缓存相关函数
const CACHE_DURATION = 30 * 24 * 60 * 60 * 1000; // 30天的毫秒数

// 保存账号信息到本地存储
function saveAccountToLocal(account, password) {
    let accounts = JSON.parse(localStorage.getItem('cachedAccounts') || '[]');
    const now = new Date().getTime();
    
    // 检查是否已存在该账号
    const existingIndex = accounts.findIndex(a => a.account === account);
    if (existingIndex !== -1) {
        accounts.splice(existingIndex, 1);
    }
    
    // 添加新账号到开头
    accounts.unshift({
        account,
        password,
        timestamp: now
    });
    
    // 清理过期账号
    accounts = accounts.filter(a => (now - a.timestamp) <= CACHE_DURATION);
    
    localStorage.setItem('cachedAccounts', JSON.stringify(accounts));
}

// 保存手机号到本地存储
function savePhoneToLocal(phone) {
    let phones = JSON.parse(localStorage.getItem('cachedPhones') || '[]');
    const now = new Date().getTime();
    
    // 检查是否已存在该手机号
    const existingIndex = phones.findIndex(p => p.phone === phone);
    if (existingIndex !== -1) {
        phones.splice(existingIndex, 1);
    }
    
    // 添加新手机号到开头
    phones.unshift({
        phone,
        timestamp: now
    });
    
    // 清理过期手机号
    phones = phones.filter(p => (now - p.timestamp) <= CACHE_DURATION);
    
    localStorage.setItem('cachedPhones', JSON.stringify(phones));
}


// 加载缓存的账号
function loadCachedAccounts() {
    const accounts = JSON.parse(localStorage.getItem('cachedAccounts') || '[]');
    const accountOptions = document.getElementById('accountOptions');
    accountOptions.style.display = 'block';
    accountOptions.innerHTML = '';
    
    accounts.forEach(acc => {
        const option = document.createElement('div');
        option.className = 'account-option';
        option.textContent = acc.account;
        option.onclick = () => selectAccount(acc.account, acc.password);
        accountOptions.appendChild(option);
    });
}

// 加载缓存的手机号
function loadCachedPhones() {
    const phones = JSON.parse(localStorage.getItem('cachedPhones') || '[]');
    const phoneOptions = document.getElementById('phoneOptions');
    phoneOptions.style.display = 'block';
    phoneOptions.innerHTML = '';
    
    phones.forEach(p => {
        const option = document.createElement('div');
        option.className = 'phone-option';
        option.textContent = p.phone;
        option.onclick = () => selectPhone(p.phone);
        phoneOptions.appendChild(option);
    });
}

// 选择账号
function selectAccount(account, password) {
    document.getElementById('account').value = account;
    document.getElementById('password').value = password;
    document.getElementById('accountOptions').style.display = 'none';
    
    // 更新选中状态样式
    const options = document.querySelectorAll('.account-option');
    options.forEach(opt => {
        opt.classList.toggle('selected', opt.textContent === account);
    });
}

// 选择手机号
function selectPhone(phone) {
    document.getElementById('phone').value = phone;
    document.getElementById('phoneOptions').style.display = 'none';
    
    // 更新选中状态样式
    const options = document.querySelectorAll('.phone-option');
    options.forEach(opt => {
        opt.classList.toggle('selected', opt.textContent === phone);
    });
}

// 添加拖拽功能（支持H5手机版触摸事件）
function enableDrag(element) {
    let isDragging = false;
    let hasMoved = false;
    let offsetX, offsetY;
    let startX, startY;
    let startTime;
    let clickTriggered = false; // 防止重复触发点击事件

    // 触摸开始事件
    element.addEventListener('touchstart', (e) => {
        isDragging = true;
        hasMoved = false;
        clickTriggered = false;
        const touch = e.touches[0];
        startX = touch.clientX;
        startY = touch.clientY;
        startTime = Date.now();
        offsetX = touch.clientX - element.getBoundingClientRect().left;
        offsetY = touch.clientY - element.getBoundingClientRect().top;
    }, { passive: true });

    // 触摸移动事件
    document.addEventListener('touchmove', (e) => {
        if (!isDragging) return;
        const touch = e.touches[0];
        const deltaX = Math.abs(touch.clientX - startX);
        const deltaY = Math.abs(touch.clientY - startY);

        // 如果移动距离超过阈值，认为是拖拽操作
        if (deltaX > 10 || deltaY > 10) {
            hasMoved = true;
            element.style.position = 'absolute';
            element.style.left = (touch.clientX - offsetX) + 'px';
            element.style.top = (touch.clientY - offsetY) + 'px';
            e.preventDefault();
        }
    }, { passive: false });

    // 触摸结束事件
    document.addEventListener('touchend', (e) => {
        if (!isDragging) return;

        const endTime = Date.now();
        const timeDiff = endTime - startTime;

        // 如果没有移动且时间很短，认为是点击操作
        if (!hasMoved && timeDiff < 500 && !clickTriggered) {
            clickTriggered = true;
            // 阻止浏览器自动触发的点击事件
            e.preventDefault();
            // 触发点击事件
            const clickEvent = new Event('click', {
                bubbles: true,
                cancelable: true
            });
            element.dispatchEvent(clickEvent);
        }

        isDragging = false;
        hasMoved = false;
        element.style.removeProperty('left'); // 清除 left 样式
    }, { passive: false });

    // 鼠标事件支持（桌面端）
    element.addEventListener('mousedown', (e) => {
        // 如果是触摸设备，忽略鼠标事件
        if ('ontouchstart' in window) return;

        isDragging = true;
        hasMoved = false;
        clickTriggered = false;
        startX = e.clientX;
        startY = e.clientY;
        startTime = Date.now();
        offsetX = e.clientX - element.getBoundingClientRect().left;
        offsetY = e.clientY - element.getBoundingClientRect().top;
        e.preventDefault();
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging || 'ontouchstart' in window) return;
        const deltaX = Math.abs(e.clientX - startX);
        const deltaY = Math.abs(e.clientY - startY);

        // 如果移动距离超过阈值，认为是拖拽操作
        if (deltaX > 10 || deltaY > 10) {
            hasMoved = true;
            element.style.position = 'absolute';
            element.style.left = (e.clientX - offsetX) + 'px';
            element.style.top = (e.clientY - offsetY) + 'px';
        }
    });

    document.addEventListener('mouseup', (e) => {
        if (!isDragging || 'ontouchstart' in window) return;

        const endTime = Date.now();
        const timeDiff = endTime - startTime;

        // 如果没有移动且时间很短，认为是点击操作
        if (!hasMoved && timeDiff < 500 && !clickTriggered) {
            clickTriggered = true;
            // 阻止浏览器自动触发的点击事件
            e.preventDefault();
            // 触发点击事件
            const clickEvent = new Event('click', {
                bubbles: true,
                cancelable: true
            });
            element.dispatchEvent(clickEvent);
        }

        isDragging = false;
        hasMoved = false;
        element.style.removeProperty('left'); // 清除 left 样式
    });
}

// 悬浮球点击事件
document.getElementById('floatBall').addEventListener('click', function() {
    this.classList.add('active');
    console.log('悬浮球点击事件:');
    showAccountCenter();
    setTimeout(() => {
        this.classList.remove('active');
        // document.getElementById('floatBall').classList.remove('active');
    }, 2000);

});

// 首页福利弹窗上一条或者下一条 type = 1 下一条 type = 2 上一条
function shouyeArticle(id,type) {
    $.post(FromUrl,{type:'shouye_fuli',uid:uid,gid:gid,cid:cid,id:id,next:type},function(html) {
        if(html.code==0){
            // layer.msg(html.msg,{time:2000});
        }else {
            // 先清除原有内容
            const ShouyeFuli = document.getElementById('ShouyeFuli');
            if (ShouyeFuli) {
                ShouyeFuli.remove();
            }
            document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
        }
    });
}

function hideShouyeFuli(){
    const ShouyeFuli = document.getElementById('ShouyeFuli');
    if (ShouyeFuli) {
        ShouyeFuli.remove();
    }
}


// 从身份证号验证年龄
function validateAgeFromID(idnum) {
    // 提取出生年月日
    let birthYear, birthMonth, birthDay;

    if (idnum.length === 18) {
        birthYear = parseInt(idnum.substring(6, 10), 10);
        birthMonth = parseInt(idnum.substring(10, 12), 10);
        birthDay = parseInt(idnum.substring(12, 14), 10);
    } else {
        // 如果是15位身份证（虽然前面正则已经限制18位，这里保留兼容性）
        birthYear = parseInt('19' + idnum.substring(6, 8), 10);
        birthMonth = parseInt(idnum.substring(8, 10), 10);
        birthDay = parseInt(idnum.substring(10, 12), 10);
    }

    // 检查日期是否有效
    if (isNaN(birthYear) || isNaN(birthMonth) || isNaN(birthDay) ||
        birthMonth < 1 || birthMonth > 12 ||
        birthDay < 1 || birthDay > 31) {
        return false;
    }

    // 计算年龄
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth() + 1;
    const currentDay = today.getDate();

    let age = currentYear - birthYear;

    // 如果生日还没过，年龄减1
    if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
        age--;
    }

    // 检查年龄是否合理（假设有效年龄在0-120岁之间）
    return age >= 8 && age <= 75;
}